<script lang="jsx" setup>
import { ref, provide, watch, computed, inject } from 'vue';
import { Button as AButton, Tag as ATag, Button, Modal, Tag, message } from 'ant-design-vue';
import { EditOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons-vue';
import { REQU, toFormData, SignInInfoInvalidCondPair, useResp } from '@/net/requ.js';
import { sexOptions } from '@/util/const.js';
import UserModal from './components/user-modal.vue';
import BaseTreeFilter from '@/components/base-tree-filter.vue';

const auth = inject('auth');

const selectedKeys = ref([]);

function handleDeselect() {
  selectedKeys.value = [];
}

function handleSelect({ key }) {
  selectedKeys.value = [key];
}

const userInfo = JSON.parse(localStorage.getItem('userInfo'));
const loading = ref(false);
const params = ref({
  orgId: userInfo?.orgId ?? '',
  start: 1,
  limit: 10,
  queryString: '',
  orderField: 'real_name',
  orderType: 'DESC',
});

watch(params, getUserList, { deep: true });

const treeData = ref();
provide('orgOptions', treeData);

// 只有登录用户同机构下的
const dataSource = ref([]);
const total = ref(0);
const columns = ref([
  {
    width: 150,
    title: '账号',
    dataIndex: 'account',
  },
  {
    width: 150,
    title: '姓名',
    dataIndex: 'realName',
  },
  {
    width: 150,
    title: '所属机构',
    dataIndex: 'orgId',
    customRender: () => '--',
  },
  {
    width: 70,
    title: '性别',
    dataIndex: 'sex',
    customRender: ({ text }) => R.propOr('--', 'label', R.find( R.propEq(text, 'value'), sexOptions )),
  },
  {
    width: 330,
    title: '角色',
    dataIndex: 'roleList',
    customRender: ({ record }) => {
      const Color = R.ifElse( R.propEq('管理员', 'roleName'), R.always('orange'), R.always('blue') )
      return R.map(
        o => (<Tag color={Color(o)}>{{ default: () => o.roleName }}</Tag>),
        record.roleList
      )
    },
  },
  {
    width: 120,
    title: '手机号',
    dataIndex: 'phoneNumber',
  },
  {
    width: 200,
    title: '邮箱',
    dataIndex: 'email',
    customRender: ({ text }) => ('null' == text || !text) && '--',
  },
  {
    width: 100,
    title: '所属分组',
    dataIndex: 'group_id',
    customRender: ({ record }) => '--',
  },
  {
    fixed: 'right',
    width: 160,
    title: '操作',
    customRender: ({ record }) => (
      <div class="op-btns icon">
        <Button
          type="link"
          onClick={() => useUserModal(record)}>
          {{
            icon: () => <EditOutlined />,
            default: () => '编辑',
          }}
        </Button>
        <Button
          type="link"
          style="color: rgb(200,0,0);"
          onClick={() => Modal.confirm({
            content: '确定删除此用户？',
            okText: '确定',
            onOk: () => delUser(record.id.toString()),
          })}>
          {{
            icon: () => <DeleteOutlined />,
            default: () => '删除',
          }}
        </Button>
      </div>
    ),
  },
]);

const selectedRowKeySet = ref(new Set());
const selectedRowKeys = computed(() => Array.from(selectedRowKeySet.value));
function onRowsSelect(record, selected) {
  const action = selected ? 'add' : 'delete';
  selectedRowKeySet.value[action](record.id);
}
function onRowsSelectAll(selected, selectedRows) {
  const action = selected ? 'add' : 'delete';
  selectedRows.forEach(row => selectedRowKeySet.value[action](row.id));
}

const roleList = ref([]);
const roleListOfUser = ref([]);
provide('roleListOfUser', roleListOfUser);

const userModalProps = ref({ visible: false });

function useUserModal(row) {
  Object.assign(userModalProps.value, { row }, { visible: true });
}

function getOrgTreeList() {
  return REQU(`/api/org/treeList`)
  .then(useResp({
    succ: result => treeData.value = result.data,
  }))
}

function getUserList() {
  loading.value = true;
  return REQU(`/api/user/list?${ new URLSearchParams(params.value) }`)
  .then(useResp({
    succ: result => {
      dataSource.value = result.data.list;
      total.value = result.data.total;
    },
    fail: R.cond([SignInInfoInvalidCondPair()]),
  }))
  .finally(() => loading.value = false);
}

function delUser(ids) {
  return REQU('/api/user/delete', {
    method: 'POST',
    body: toFormData({ ids }),
  })
  .then(useResp({
    succ: result => {
      message.success('删除成功');
      selectedRowKeySet.value.clear();
      getUserList();
    },
    fail: result => {
      message.error(result.message || '删除失败');
    },
  }));
}

function getRoleListOfUser() {
  return REQU('/api/user/userRoleList', { method: 'GET' })
  .then(useResp({
    succ: result => roleListOfUser.value = result.data,
  }));
}

function getRoleList() {
  // loading.value = true;
  return REQU(`/api/role/list?${ new URLSearchParams({
    orgId: userInfo.orgId ?? '',
    start: 1,
    limit: 100,
    queryString: '',
    orderField: 'role_name',
  }) }`)
  .then(useResp({
    succ: result => {
      roleList.value = result.data.list;
    }
  }))
  // .finally(() => loading.value = false)
}

function main() {
  getOrgTreeList();
  getUserList();
  getRoleListOfUser();
  // getRoleList();
}

main();
</script>

<template>
  <div class="user-manage">
    <base-tree-filter title="组织架构" searchable>
      <a-menu
        v-model:selectedKeys="selectedKeys"
        mode="inline"
        multiple
        :inlineIndent="10"
        @deselect="handleDeselect"
        @select="handleSelect"
      >
        <template v-for="item in treeData" :key="item.id">
          <a-menu-item>{{ item.name }}</a-menu-item>
        </template>
      </a-menu>
    </base-tree-filter>

    <header>
      <a-button
        v-if="auth"
        type="primary"
        @click="() => useUserModal()"
      >
        + 添加成员
      </a-button>
      <a-button
        type="danger"
        :disabled="!selectedRowKeys.length"
        ghost
        @click="() => Modal.confirm({
          content: '确定删除已选的用户？',
          okText: '确定',
          onOk: () => delUser(selectedRowKeys.join(',')),
        })"
      >
        删除
      </a-button>

      <div class="filter">
        <a-input
          placeholder="输入编号 / 姓名搜索"
          allow-clear
          style="width: 200px; margin-left: auto; border-radius: 18px;">
          <template #prefix>
            <search-outlined style="color: rgb(181,181,181);" />
          </template>
        </a-input>
      </div>
    </header>

    <main>
      <header>
        <h4>{{ total }}人</h4>
      </header>
      <a-table
        :show-header="0 < dataSource.length"
        :loading="loading"
        :data-source="dataSource"
        :columns="columns"
        row-key="id"
        :scroll="{ x: 1360 }"
        :row-selection="{
          fixed: true,
          selectedRowKeys,
          onSelect: onRowsSelect,
          onSelectAll: onRowsSelectAll,
        }"
        @change="pagination => params.start = pagination.current"
        :pagination="{
          current: params.start,
          pageSize: params.limit,
          total,
          pageSizeOptions: ['10', '20', '50'],
          showQuickJumper: true,
          showSizeChanger: true,
          position: ['bottomCenter'],
        }"
      >
      </a-table>
    </main>

    <user-modal
      v-if="userModalProps.visible"
      v-model:visible="userModalProps.visible"
      :row="userModalProps.row"
      @ok="() => getUserList()">
    </user-modal>
  </div>
</template>

<style>
.user-manage {
  display: grid;
  gap: 16px;
  grid-template-areas:
    'aside header'
    'aside .';
  grid-template-rows: auto 1fr;
  grid-template-columns: 240px 1fr;
  padding: 24px;
}

.user-manage .tree-filter { grid-area: aside; }

.user-manage > header {
  grid-area: header;
  display: flex;
  flex-wrap: wrap;
  gap: 1em;
}

.user-manage > header > .filter { margin-left: auto; }

.user-manage > main {
  overflow-x: hidden;
  padding: 24px;
  background: #fff;
  border-radius: 6px;
}

.user-manage > main > header { margin-bottom: 24px; }

.user-manage > main > header h4 {
  font-size: 16px;
  font-weight: 700;
  color: rgba(0,0,0,.6);
}
</style>
